package cn.minimelon.bittermelon.utils;

import cn.minimelon.bittermelon.bean.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.noear.solon.Utils;

import java.security.Key;
import java.util.Date;

public class JwtUtils {
    public static final String SUBJECT = "MiniMelon";

    public static final long EXPIRE_WEEK = 1000 * 60 * 60 * 24 * 7;  // 过期时间，毫秒，一周
    public static final long EXPIRE_HOUR = 1000 * 60 * 60;  // 过期时间，毫秒，一小时
    public static final long EXPIRE_MINUTE = 1000 * 60;  // 过期时间，毫秒，一分钟

    public static String getJwt(LoginUser user, Key key, long expire) {
        if(user == null || Melon.isEmpty(user.getId()) || Melon.isEmpty(user.getName())) {
            return null;
        }

        String token = Jwts.builder()
                .claim("id", user.getId())
                .claim("name", user.getName())
                .claim("code", user.getCode())
                .claim("avatar", StringUtils.nullToEmpty(user.getAvatar()))
                .setIssuer("solon")
                .setAudience("melon.client")
                .setSubject(SUBJECT)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .setId(Utils.guid())
                .signWith(key).compact();
        return token;
    }

    public static String getUIJwt(LoginUser user, Key key) {
        return getJwt(user, key, EXPIRE_WEEK);
    }

    public static String getRESTJwt(LoginUser user, Key key) {
        return getJwt(user, key, EXPIRE_MINUTE);
    }

    public static String getJOBJwt(LoginUser user, Key key) {
        return getJwt(user, key, EXPIRE_HOUR);
    }

    public static Claims checkJwt(String token, Key key) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
